package com.beyondtherack;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.archive.crawler.datamodel.CrawlURI;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.filters.AndFilter;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.dao.DBUtil;
import com.dao.DealBean;
import com.util.CategoryMapping;

public class BeyondTheRackHtmlParser {
	
	public  void parserBeyondTheRack(CrawlURI curi) throws Exception{
		
		String url = curi.toString();
		
		System.out.println(url);
		
		DealBean beyondtherackBean = new DealBean();
		
		beyondtherackBean.setBuy_url(url);
		
        String souceSite = "BeyondTheRack";
        
        beyondtherackBean.setSouce_site(souceSite);
        
        String brand = "";
        
        beyondtherackBean.setBrand(brand);
        
        String modelId = "";
        
        beyondtherackBean.setModel_id(modelId);
        
        if(curi.getCategory1() != null){
        	
        	String category1 = CategoryMapping.getType1(curi.getCategory1());
            
            System.out.println(category1);
            
            beyondtherackBean.setCategory1(category1);
        	
        }
        
		Parser parser;
		
		String skuId = "";
		
		try {
			
			parser = new Parser(url);
			
			parser.setEncoding("UTF-8");
			
            NodeFilter clearfixFilter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("class", "clearfix"));
            
            NodeList clearfixList = parser.extractAllNodesThatMatch(clearfixFilter); 
            
            if (clearfixList != null && clearfixList.size() > 0) {  

                Node clearfixNode = clearfixList.elementAt(3); 
                
                Parser clearfixparser = new Parser(clearfixNode.toHtml());
                
                NodeFilter nodeFilter = new TagNameFilter("div");
                
                NodeList nodeList = clearfixparser.extractAllNodesThatMatch(nodeFilter); 
                
                if (nodeList != null && nodeList.size() > 0) {  

                    Node priceNode = nodeList.elementAt(0);
                    
                    Parser priceparser = new Parser(priceNode.toHtml());
                    
                    NodeFilter originalPriceFilter = new AndFilter(new TagNameFilter("span"),new HasAttributeFilter("class", "product-price-prev"));
                    
                    NodeFilter salePriceFilter = new AndFilter(new TagNameFilter("span"),new HasAttributeFilter("class", "product-price red"));
                    
                    NodeList originalPriceList = priceparser.extractAllNodesThatMatch(originalPriceFilter);
                    
                    if (originalPriceList != null && originalPriceList.size() > 0) {
                    	
                    	Node originalPriceNode = originalPriceList.elementAt(0);
                    	
                    	String originalPrice = originalPriceNode.toPlainTextString().trim();
                    	
                    	beyondtherackBean.setOriginal_price(originalPrice);
                    	
                    }
                    
                    priceparser.reset();
                    
                    NodeList salePriceList = priceparser.extractAllNodesThatMatch(salePriceFilter);
                    
                    if (salePriceList != null && salePriceList.size() > 0) {
                    	
                    	Node salePriceNode = salePriceList.elementAt(0);
                    	
                    	String salePrice = salePriceNode.toPlainTextString().trim();
                    	
                    	beyondtherackBean.setSale_price(salePrice);
                    	
                    }
                    
                    if(nodeList.elementAt(2)!= null){
                    	
                    	Node skuIdNode = nodeList.elementAt(2);
                    	
                    	String sku_Id = skuIdNode.toPlainTextString().trim();
                    	
                    	String[] sku_id = sku_Id.split(" ");
                    	
                    	skuId = sku_id[1];
                    	
                    	beyondtherackBean.setSku_id(skuId);
                    	
                    }
                }
            }
            
            parser.reset();
            
            NodeFilter imageUrlFilter = new AndFilter(new TagNameFilter("a"),new HasAttributeFilter("id", "zoom1"));
			 
			 NodeList imageUrlList = parser.extractAllNodesThatMatch(imageUrlFilter);
			             
			    if (imageUrlList != null && imageUrlList.size() > 0) { 
			             	
			             Tag imageUrlNode = (Tag) imageUrlList.elementAt(0);
			                 
			             String imageUrl = imageUrlNode.getAttribute("href");
			                 
			             beyondtherackBean.setImage_url(imageUrl);
			             
			             }
			    
			 parser.reset();
		          
	         NodeFilter productNameFilter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("style", "font-size: 20px; font-weight: 900;"));
				 
			 NodeList productNameList = parser.extractAllNodesThatMatch(productNameFilter);
				             
				 if (productNameList != null && productNameList.size() > 0) { 
				    	
				      Node productNameNode = productNameList.elementAt(28);
		                 
		              String productName = productNameNode.toPlainTextString().trim();
		                 
		              beyondtherackBean.setProduct_name(productName);
		             
				    }
			 parser.reset();
		          
	         NodeFilter itemFilter = new TagNameFilter("title");
				 
			 NodeList itemList = parser.extractAllNodesThatMatch(itemFilter);
				             
				  if (itemList != null && itemList.size() > 0) { 
				    	
				     Node itemNode = itemList.elementAt(0);
		                 
		             String item = itemNode.toPlainTextString().trim();
		             
		             String category2 = CategoryMapping.getType2(item);
		             
		             System.out.println("@@"+category2);
		             
		             if(category2 == null){
		            	 
		            	 beyondtherackBean.setCategory2(""); 
		            	 
		             }
		                 
		             beyondtherackBean.setCategory2(category2);
		             
				    	}
				  
				  parser.reset();
		             
		             NodeFilter productDescriptionFilter = new AndFilter(new TagNameFilter("ul"),new HasAttributeFilter("style", "padding-left: 15px; font-size: 15px; "));
		             
		             NodeList productDescriptionList = parser.extractAllNodesThatMatch(productDescriptionFilter);
		              
		               if (productDescriptionList != null && productDescriptionList.size() > 0) { 
		            	   
		             	    Node productDescriptionNode = productDescriptionList.elementAt(0);
		                 	
		                 	String productDescription = productDescriptionNode.toPlainTextString().trim();
		                 	
		                 	beyondtherackBean.setProduct_description(productDescription);

		               }
		               parser.reset();
			             
			             NodeFilter endsTimeFilter = new AndFilter(new TagNameFilter("div"),new HasAttributeFilter("id", "eventTTL"));
			             
			             NodeList endsTimeList = parser.extractAllNodesThatMatch(endsTimeFilter);
			              
			               if (endsTimeList != null && endsTimeList.size() > 0) { 
			            	   
			             	    Node endsTimeNode = endsTimeList.elementAt(0);
			                 	
			                 	String endsTime = endsTimeNode.toPlainTextString().trim();
			                 	
			                 	beyondtherackBean.setEnds_time(endsTime);
	
			               }
			    
		} catch (ParserException e) {
			
			e.printStackTrace();
		}  
        
		 DBUtil db = new DBUtil();
         
         if(beyondtherackBean.getSku_id()!=null){
         
         db.save(beyondtherackBean);
         
         }
         
		
	}
	
	 private static void saveFile(String imgString, String productId) throws Exception {
		  	URL url;
		  	File outFile;
		  	OutputStream os = null;
		  	InputStream is = null;
				try {
					url = new URL(imgString);
					outFile = new File("C:/nordstrom/img/"+productId+".jpg");
					os = new FileOutputStream(outFile);
					is = url.openStream();
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				byte[] buff = new byte[1024];
				while(true) {
					int readed = is.read(buff);
					if(readed == -1) {
						break;
					}
					byte[] temp = new byte[readed];
					System.arraycopy(buff, 0, temp, 0, readed);
					os.write(temp);
				}
				is.close(); 
		      os.close();
			}

}
